package com.github.apollo.handler;

import com.github.apollo.model.Person;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @author Stephen
 * @since 2018-02-06
 */
public class PersonHandler {

    private List<Person> person;

    public PersonHandler() {
        Person jack = new Person();
        jack.setName("jackson");
        jack.setAddress("LA");
        jack.setGender("M");

        Person marry = new Person();
        marry.setName("marry");
        marry.setAddress("NY");
        marry.setGender("F");

        person = Arrays.asList(jack, marry);
    }



    public Mono<ServerResponse> listAll(ServerRequest request) {

        Flux<Person> all = Flux.fromIterable(person);
        return ServerResponse.ok()
            .contentType(MediaType.APPLICATION_JSON)
            .body(all, Person.class);
    }

    public Mono<ServerResponse> create(ServerRequest request) {

        Mono<Person> body = request.bodyToMono(Person.class);

        System.out.println(body);

        return ServerResponse.ok().build();
    }

    public Mono<ServerResponse> getPerson(ServerRequest request) {

        String name = request.pathVariable("name");
        Mono<Person> response = Mono.empty();
        for (Person p : person) {
            if (p.getName().equals(name)) {
                response = Mono.just(p);
                break;
            }
        }

        return response.flatMap(x -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromObject(x)))
            .switchIfEmpty(ServerResponse.notFound().build());
    }
}
